<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/12/26
 * Time: 下午3:47
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\res\XhresArticle;
use Admin\Models\school\XhschoolCaseShare;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolShare;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysGrade;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\UserPower;
use Helpers\XhException;

class SchoolShareController extends  ControllerBase
{

    public static $enums = [
        'iArea' => [1 => '部门' , 2 => '区域' ,3 => '市' ],
    ];

    public function schoolShareAction()
    {
        $this->view->pick('school_share/schoolShare');
        Assets::viewer();
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/school_share/schoolShare.js');
        $this->view->setVars([
            'addSharePower' => UserPower::checkUserPower('School_Share_Add'),
        ]);
    }


    public function saveShareAction()
    {
        try{
            $iSSId = $this->request->getPost('iSSId');
            $iSchoolId = $this->request->getPost('iSchoolId') or die('缺少参数');
            if($iSSId){
                if(!UserPower::checkUserPower('School_Share_Edit')){
                    return $this->sendErrorResponse(400,'缺少编辑权限');
                }
                $obj = XhschoolShare::findFirst($iSSId);
            }else{
                if(!UserPower::checkUserPower('School_Share_Add')){
                    return $this->sendErrorResponse(400,'缺少新增权限');
                }
                $obj = new XhschoolShare();
            }
            $obj->assign($this->request->getPost());
            if($obj->save()){
                return $this->sendSuccessResponse('保存成功');
            }else{
                return $this->sendErrorResponse(500,'保存失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function getShareDataAction()
    {
        if (!UserPower::checkUserPower('School_Share')) {
            return $this->sendErrorResponse(400, '缺少权限');
        }
        $schoolId = $this->request->getPost('schoolId');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $objs = XhschoolShare::find([
            'conditions' => 'bDelete = 0 AND iSchoolId = :iSchoolId:',
            'bind'       => ['iSchoolId' => $schoolId],
            'order'      => 'tTime desc,tCreateDate desc',
        ]);
        $showDelete = UserPower::checkUserPower('School_Share_Del');
        $showEdit   = UserPower::checkUserPower('School_Share_Edit');
        return $this->sendJsonResponse(array(
            'showDelete' => $showDelete,
            'showEdit' => $showEdit,
            'data' => $this->pkData($objs->toArray())
        ));
    }

    /**
     * @param $shareData
     * @return array
     *
     * modify by sqb 20181221
     */
    private function pkData($shareData)
    {
        $filePath = Main::getConfigByName('customer')['downUrl'];
        $newArray = [];
        Main::runUserNameById($shareData, ['iLastModifyUserId'=>'sLastModifyUserName',
            'iCreateUserId'=>'sCreateUserName'], true);
        Tool::runEnum($shareData, ['iGrade' => XhsysEnum::getEnumByNodeName('年级')]);
        $ids = array_values(array_unique(array_filter(array_column($shareData,'iCreateUserId'))));
        $powerArr = $this->checkPower($ids);
        foreach ($shareData as $data) {
            $item = array(
                'imgPath' => $filePath,
                'filePath' => $filePath,
                'images' => $data['sImages'],
                'files' => $data['sFiles'],
                'footer' => array(
                    'left' => '修改时间:' . $data['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . $data['sLastModifyUserName'],
                    'right' => '创建时间:' . $data['tCreateDate'] . '&nbsp;&nbsp;创建人:' . $data['sCreateUserName'],
                ),
                'showCheck' => $powerArr[$data['iCreateUserId']],
            );
            $item['id']      = $data['iSSId'];
            $item['title']   = '<b>时间:</b>&nbsp;&nbsp;' . date('Y-m-d H:i', strtotime($data['tTime']));
            $item['title']  .='&nbsp;&nbsp;&nbsp;&nbsp;<b>地点:</b>'.$data['sPlace'];
            $item['title']  .='&nbsp;&nbsp;&nbsp;&nbsp;<b>年级:</b>'.$data['iGrade'];
            $item['time']    =  $data['tTime'];
            $item['content'] = str_replace(array("\r\n", "\r", "\n"), '<br />', $data['mContent']);

            if ($data['iState'] == 1) {
                $item['retain'] .= '<div style="position:absolute;height: 70px;width: 70px;z-index: 0;bottom: 0px;right: 10px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/f3f03dfae59741e1b1529c6f10bc7e37.png" style="width: 100%;height: 100%;opacity: 0.2;"></div>';
            } else if($data['iState'] == 2) {
                $item['retain'] .= '<div style="position:absolute;height: 70px;width: 70px;z-index: 0;bottom: 0px;right: 10px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/ccb87932a83a440ca717eeb00ddd8ef4.png" style="width: 100%;height: 100%;opacity: 0.2;"></div>';
            } else if($data['iState'] == 3) {
                $item['retain'] .= '<div style="position:absolute;height: 70px;width: 87px;z-index: 0;bottom: 0px;right: 10px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/b392e44af9674f0cb56fb279a5b79e14.png" style="width: 100%;height: 100%;opacity: 0.5;"></div>';
            }

            $newArray[]=$item;
        }
        return $newArray;
    }

    /**
     * @param $ids
     * @return array
     */
    public function checkPower($ids){
        if($ids ==[]){
            return [];
        }
        $powerArr = [];

        $powerIds = Hrm::getInChargeUserIds();
        if(is_bool($powerIds) === true){
            foreach ($ids as $id){
                $powerArr[$id] = $powerIds;
            }
        }else{
            $powerIds = array_column($powerIds,'iUserId','iUserId');
            foreach ($ids  as $id){
                if(isset($powerIds[$id])){
                    $powerArr[$id] = true;
                }else{
                    $powerArr[$id] = false;
                }
            }
        }
        return $powerArr;
    }

    /**
     * 审核
     *
     * create by sqb 20181221
     */
    public function checkAction()
    {
        UserPower::checkUserPower('School_Share_Check') or  die('没有该权限');
        $iSSId = $this->request->getQuery('iSSId');
        $this->view->pick('school_share/check');
        Assets::importJs('js/school_share/check.js');

        $shareInfo = XhschoolShare::findFirst($iSSId);

        if ($shareInfo) {
            $shareInfo = $shareInfo->toArray();
        } else {
            $shareInfo = [];
        }

        $this->view->setVars([
            'shareInfo' => json_encode($shareInfo),
        ]);
    }

    /**
     * create by sqb 20181221
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function saveShareCheckAction()
    {
        UserPower::checkUserPower('School_Share_Check') or  die('没有该权限');

        try {
            $iSSId = $this->request->getPost('iSSId', 'int');

            $shareInfo = XhschoolShare::findFirst($iSSId);

            $shareInfo->iState = $this->request->getPost('iState');
            $shareInfo->mCheck = $this->request->getPost('mCheck');

            if ($shareInfo->save()) {
                return $this->sendJsonResponse('操作成功');
            }

            return $this->sendJsonResponse('操作失败');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 设置优秀文章
     * @param $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180509
     * modify by dale 20180815   弃用
     */
    public function setExcellentAction($type=null){
        $data = $this->request->getPost();
        $obj = XhresArticle::findFirst($data['iArtId']);
        if( !$type ){
            $obj->bExcellent = 1;
            $obj->sExMonth = date('Y-m',time());
        }else if ($type =='cancel') {
            $obj->bExcellent = 0;
            $obj->sExMonth = '';
        }
        if(!$obj->save()) {
            return $this->sendErrorResponse(500,'保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }



    public function delShareAction(){
        if(!UserPower::checkUserPower('School_Share_Del')){
            return $this->sendErrorResponse(400,'缺少删除权限');
        }
        $iSSId = $this->request->getPost('iSSId','int');
        if(!$iSSId){
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $share = XhschoolShare::findFirst([
            'conditions' => 'bDelete = 0 AND iSSId = :iSSId:',
            'bind'       => ['iSSId' => $iSSId]
        ]);
        if (!$share) {
            return  $this->sendErrorResponse(500,'找不到该记录');
        }
        if($share->iCreateUserId != Main::getLoginUserInfo('userId')
            && Main::getLoginUserInfo('logonName') != 'admin'){
            return $this->sendErrorResponse(500,'缺少权限');
        }
        $share->bDelete = 1;
        if(!$share->save()){
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('成功');
    }

    public function shareFormAction()
    {
        $ssId = $this->request->getQuery('ssId');
        $this->view->pick('school_share/shareForm');
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('../customer/js/fileinput.min.js')//修改过的
            ->addJs('../customer/js/zh.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::datetimePicker();
        Assets::importJs('js/school_share/shareForm.js');
        $check = '';
        if (!$ssId) {
            $info = '1';
        } else {
            $info = XhschoolShare::findFirst($ssId)->toArray();
            if (!UserPower::checkUserPower('School_Share_Edit')) {
                $check = "<script>parent.$('#bt_modal_confirm').hide();</script>";
            } elseif (Main::getLoginUserInfo('logonName') !='admin' && $info['iCreateUserId'] != Main::getLoginUserInfo('userId')) {
                $check = "<script>parent.$('#bt_modal_confirm').hide();</script>";
            }
            $info = json_encode($info);
        }
        $this->view->setVars([
            'info' => $info,
            'check' => $check,
            'gradeArr' => XhsysEnum::getEnumByNodeName('年级'),
        ]);
    }

    /**
     * ajax上传
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by dale 201812
     */
    public function ajaxUploadAction(){

        $this->view->disable();
        $schoolId = $this->request->getQuery('schoolId', 'string');
        if(!$schoolId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $this->request->hasFiles() or die('没有文件上传');

        $file = $this->request->getUploadedFiles()[0];
        $savePath = Main::getConfigByName('customer')['savePath'];

        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true) or die($savePath . '创建失败');
        }
        $root = realpath($savePath);
        substr($root, strlen($root) - 1, strlen($root)) == '/' or $root .= '/';

        $extension = strtolower($file->getExtension());

        if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif' || $extension == 'jpeg') {
            $subDirName = '/img/';
        } else {
            $subDirName = '/file/';
        }
        $dirPath = $root . 'school_share'.$schoolId . $subDirName;
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0777, true) or die($dirPath . '创建失败');
        }
        $url = 'school_share'.$schoolId . $subDirName . md5_file($file->getTempName()) . '.' . $file->getExtension();
        $filePath = $dirPath . md5_file($file->getTempName()) . '.' . $file->getExtension();

        $name = $file->getName();
        $file->moveTo($filePath);

        return json_encode(array('url' => $url, 'fileName' => $name));
    }

    /**
     * 删除图片,更新数据库中记录,删除服务器上的文件
     *
     * created by dale 2017/6/30 下午3:23
     *
     */
    public function ajaxDeleteAction()
    {
        $this->view->disable();
        $id = $this->request->getPost('id', 'string') or die('缺少参数id');
        $rmId = $this->request->getPost('rmId', 'int');
        if ($rmId == null) {
            die('缺少参数');
        }
        $obj = XhschoolShare::findFirst($id);
        $image = $obj->toArray();
        $images = explode(',', $image['sImages']);
        $url = '';
        foreach ($images as $key => $value) {
            if ($key != $rmId && $value != '') {
                $url = $url . $value . ',';
            }
        }
        $obj->sImages = $url;
        $result = $obj->save();
        $showDelete = UserPower::checkUserPower('School_Share_Del');
        if ($result) {
            $obj = XhschoolShare::find($id);
            return json_encode(array(
                'showDelete' => $showDelete,
                'data' => $this->pkData($obj->toArray())[0],
            ));
        }
        return false;
    }

    /**
     * 学校分享首页
     *
     * @param $schoolId
     *
     * create by dale 20180259
     */
    public function homeAction($schoolId){
        $this->view->pick('school_share/home');
        $shares = XhschoolShare::find([
            'conditions' => " bDelete = 0 AND iSchoolId = :schoolId: ",
            'bind' => [ 'schoolId' => $schoolId ]
        ])->toArray();
        $this->view->setVars([
            'schoolName' => XhschoolInfo::getSchoolArray()[$schoolId],
            'shares'     => $shares,
            'showMore'   => false,
        ]);
    }


    /**
     * 案例分享列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale 20180416
     */
    public function caseShareListAction(){
        $schoolId = $this->request->getQuery('schoolId', 'int');
        Assets::easyUI();
        Assets::importJs('js/school_share/caseShareList.js');
        $this->view->pick('school_share/caseShareList');
        Template::exists('XHSchool_CaseShare', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();

        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search',
            'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'XHSchool_CaseShare', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'schoolId'       => $schoolId,
        ]);
    }

    /**
     * 编辑
     *
     * @param $schoolId
     * @param $iSCSId
     * create by dale 20180417
     */
    public function caseShareFormAction($schoolId=null,$iSCSId=null){
        $this->view->pick('school_share/caseShareForm');
        Assets::datetimePicker();
        Assets::importJs('js/school_share/caseShareForm.js');

        $webArr  = [];
        $webArr['iSchoolId'] = $schoolId;
        $webArr['iArea'] = self::$enums['iArea'] ;
        if($iSCSId){
            $info = XhschoolCaseShare::findFirst($iSCSId);
            $webArr['info'] = json_encode($info->toArray());
        }

        $this->view->setVars($webArr);
    }

    /**
     * 获取case
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180416
     */
    public function getCaseAction($schoolId){
        $key = $this->request->getPost('key','string');
        $builder = $this->modelsManager->createBuilder()
            ->columns('s.iSCSId,s.iArtId,s.iSchoolId,s.iArea,s.tTime,s.mDesc,s.tCreateDate,s.iCreateUserId,s.tLastModifyDate,s.iLastModifyUserId,a.sTitle')
            ->from(['s'=>'Admin\\Models\\school\\XhschoolCaseShare'])
            ->leftJoin('Admin\\Models\\res\\XhresArticle','a.iArtId = s.iArtId ','a')
            ->where('s.bDelete = 0 ' );
        if ($schoolId && $schoolId != 'null') {
            $builder->andWhere(' s.iSchoolId = :iSchoolId: ' , [ 'iSchoolId' => $schoolId ]);
        }
        if ($key) {
            $builder->andWhere(' a.sTitle like :key: ',[ 'key' => '%'.$key.'%' ] );
        }

        $data = Main::runBuilderPage($builder,self::$enums);
        Main::runUserNameById($data['rows'],['iCreateUserId' => 'iCreateUserId','iLastModifyUserId' => 'iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }


    /**
     * 保存case
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180416
     */
    public function saveCaseAction(){
        $data = $this->request->getPost();
        try{
            if (isset($data['iSCSId']) && $data['iSCSId'] != '' ) {
                $obj = XhschoolCaseShare::findFirst($data['iSCSId']);
            } else {
                $obj = new XhschoolCaseShare();
            }
            $obj->assign($data);
            if (!$obj->save()) {
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e) {
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 删除case
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180416
     */
    public function delCaseAction(){
        $ids = $this->request->getPost('ids');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        try{
            $this->db->begin();
            $objs = XhschoolCaseShare::find([
                'conditions' => 'iSCSId in  ({ids:array}) AND bDelete = 0',
                'bind'       => ['ids' => $ids]
            ]);
            foreach ($objs as $obj) {
                $obj->bDelete = 1;
                if(!$obj->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 案例打分
     *
     * create by xjq 20180601
     */
    public function caseGradeAction(){
        $this->view->pick('school_share/caseGrade');
        Assets::importJs('js/school_share/caseGrade.js');
        $this->view->setVar('schoolId' , $this->request->getQuery('schoolId'));
    }


    /**
     * 保存成绩
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180601
     */
    public function saveGradeAction(){
        $postData = $this->request->getPost();
        if (isset($postData['iRecId']) && $postData['iRecId']) {
            $obj = XhsysGrade::findFirst($postData['iRecId']);
        }else{
            $obj = XhsysGrade::findFirst([
                'conditions' => 'bDelete = 0  and iTargetId = :iTargetId:  and sMonth = :sMonth: and iType = 1  ',
                'bind'       => [ 'iTargetId' => $postData['iTargetId'], 'sMonth' => $postData['sMonth']],
            ]);
            if (!$obj ) {
                $obj = new XhsysGrade();
            }else{
                return $this->sendErrorResponse(500 , '当月成绩已经生成请勿重复生成');
            }
        }
        $obj->assign($postData);
        $obj->iType = 1;//只限运营案例成绩
        if (!$obj->save()) {
            return $this->sendErrorResponse(500 , '保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }

    /**
     * 成绩列表
     *
     * create by xjq 20180601
     */
    public function gradeListAction(){
        $this->view->pick('school_share/gradeList');
        $grades = XhsysGrade::find([
            'conditions' =>  'bDelete = 0 and iTargetId = :iTargetId: and iType = 1 ',
            'bind'       => ['iTargetId' => $this->request->getQuery('schoolId','int') ]
        ])->toArray();
        Main::runUserNameById($grades , ['iCreateUserId' => 'iCreateUserId'] , true );
        $this->view->setVar('grades' , $grades);
    }

}
